# -*- coding: utf-8 -*
# @Time : 2022/1/25 17:59

from src.User.Database.user_database import User
from src.User.Database.user_database import UserSchema
from src.ApiTest.ProjectInfo.Database.project_database import Project, ProjectSchema
from Common.yaml_method import YamlMethod
import ast


class ProjectList:
    """
    获取项目列表接口
    """

    @staticmethod
    def project_list(user_id=None):
        """
        获取项目列表接口
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        info = []

        if user_id:
            user = User.query.filter_by(id=user_id).first()
            user_schema = UserSchema()
            user_data = user_schema.dump(user)
            user_project_id = user_data['user_projects']
            id_list = ast.literal_eval(user_project_id)
            for i in id_list:
                project_info = Project.query.filter_by(id=i).first()
                project_schema = ProjectSchema()
                project_data = project_schema.dump(project_info)
                info.append(project_data)
        else:
            data = Project.query.all()
            for i in data:
                project_schema = ProjectSchema()
                project_data = project_schema.dump(i)
                # 将单条数据库信息添加到info中
                info.append(project_data)

        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'projectList': info,
            }
        }

        return res
